//
//  NetRequest.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/8/20.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "NetRequest.h"


#import <SDWebImage/UIImageView+WebCache.h>

@interface NetRequest(){
    MBProgressHUD *  _hud;
}

@end

@implementation NetRequest
+(instancetype)request{
    NetRequest * request = [[[self class] alloc] initWithBaseURL:nil];
    request.requestSerializer = [AFHTTPRequestSerializer serializer];
    return request;
}

-(void)GetWithUrl:(NSString *)url prama:(NSDictionary *)prama requestHandle:(RequestHandle)handle{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [self showHudWithText:@""];
    self.handle = handle;
    [self GET:url parameters:prama progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSDictionary * dict;
        [self hiddenHud];
        if([responseObject isKindOfClass:[NSData class]]){
            dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        }
        if([responseObject isKindOfClass:[NSDictionary class]]){
            dict = responseObject;
        }
        if([dict[@"code"] integerValue]==200){
            if(self.handle){
                self.handle(YES,dict);
            }
        }else{
            NSLog(@"%@",responseObject);
            if(self.handle){
                self.handle(NO,dict);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenHud];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            NSLog(@"\n%@\n",error);
        if(self.handle){
            self.handle(NO,@{@"error":error.localizedDescription});
        }
    }];
    

}



-(void)PostWithUrl:(NSString *)url prama:(NSDictionary *)prama requestHandle:(RequestHandle)handle{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    self.handle = handle;
     [self showHudWithText:@""];
    [self POST:url parameters:prama constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [self hiddenHud];
        NSDictionary * dict;
        if([responseObject isKindOfClass:[NSData class]]){
            dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        }
        if([responseObject isKindOfClass:[NSDictionary class]]){
            dict = responseObject;
        }
        if([dict[@"code"] integerValue]==200){
            if(self.handle){
                self.handle(YES,dict);
            }
        }else{
            if(self.handle){
                self.handle(NO,dict);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"%@",error);
        [self hiddenHud];
        if(self.handle){
            self.handle(NO,@{@"error":error.localizedDescription});
        }
    }];
}


-(void)PostWithUrl:(NSString *)url prama:(NSDictionary *)prama data:(NSData *)data name:(NSString *)name filename:(NSString *)fileName type:(NSString *)type requestHandle:(RequestHandle)handle{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    self.handle = handle;
     [self showHudWithText:@""];
    [self POST:url parameters:prama constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:name fileName:fileName mimeType:type];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [self hiddenHud];
        NSDictionary * dict;
        if([responseObject isKindOfClass:[NSData class]]){
            dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        }
        if([responseObject isKindOfClass:[NSDictionary class]]){
            dict = responseObject;
        }
        if([dict[@"code"] integerValue]==200){
            if(self.handle){
                self.handle(YES,dict);
            }
        }else{
            if(self.handle){
                self.handle(NO,dict);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        [self hiddenHud];
        NSLog(@"%@",error);
        if(self.handle){
            self.handle(NO,@{@"error":error.localizedDescription});
        }
    }];
}

-(void)downloadImageWithUrl:(NSString*)url requestHandle:(RequestHandle)handle{
    

    
    [self downloadImageWithUrl:url requestHandle:handle useWebCace:NO];
}


-(void)downloadImageWithUrl:(NSString*)url requestHandle:(RequestHandle)handle useWebCace:(BOOL)useWebCace{
    self.handle = handle;
    __block  NSData * data;
    __block UIImage * image;
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    if([[url uppercaseString] containsString:@"HTTP"]){
        
    }else{
        url=[url addHeader:[NSString stringWithFormat:@"%@/",host]];
    }
    
    if(useWebCace){
        [[[UIImageView alloc] init] sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:false];
            if(self.handle){
                if(image)
                    self.handle(YES,image);
                else
                    self.handle(NO,nil);
            }
        }];
    }else{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            image = [UIImage imageWithData:data];
            if ([NSThread isMainThread])
            {
                [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                if(self.handle){
                    if(image)
                        self.handle(YES,image);
                    else
                        self.handle(NO,nil);
                }
            }
            else
            {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                    if(self.handle){
                        if(image)
                            self.handle(YES,image);
                        else
                            self.handle(NO,nil);
                    }
                });
            }
        });
    }
   
}

-(void)showHudWithText:(NSString*)text{
    return;
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    _hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    _hud.labelText = text;
}

-(void)hiddenHud{
    [_hud hide:YES];
}
@end
